//
//  CQViewController.m
//  JDSideMenu
//  主地图界面
//  Created by 常 琼 on 14-9-27.
//  Copyright (c) 2014年 Markus Emrich. All rights reserved.
//

#import "CQViewController.h"
#import "BMKMapView.h"
#import "BMapKit.h"
#import "SHLogin.h"
#import "HMNavigationController.h"
#import "HMMainViewController.h"
#import "SHAddressGuide.h"
#import "SHTableViewController.h"
#import "SHSearch2ViewController.h"


#import "MLAudioRecorder.h"
#import "AmrRecordWriter.h"
#import <AVFoundation/AVFoundation.h>
#import "MLAudioMeterObserver.h"

#import "MLAudioPlayer.h"
#import "AmrPlayerReader.h"

#import "ASIFormDataRequest.h"
#import "ASIHTTPRequest.h"


#import "ToastView.h"

#define CIRCLE_OX 89
#define CIRCLE_OY 117 + 64
#define CIRCLE_S 142
#define NOT_FOR_IOS7 64



@interface CQViewController ()<BMKGeneralDelegate,BMKLocationServiceDelegate,BMKMapViewDelegate>
{
    //IOS8适配
   CLLocationManager *locationManager;
}



@property (weak, nonatomic) IBOutlet UILabel *address;

@property (strong, nonatomic) IBOutlet UIButton *buttonCover;

//我的位置
@property(nonatomic,assign) CLLocationDegrees longitude;
@property(nonatomic,assign) CLLocationDegrees latitude;


@property(nonatomic,strong) BMKMapManager *manager;
@property(nonatomic,weak) UIButton  *button;
@property(nonatomic,strong)  BMKMapView  *mapview;
@property(nonatomic,strong) UIButton *returnBtn;
@property(nonatomic,strong) UIButton *btnmac;//麦克风按钮
@property(nonatomic,strong)  BMKLocationService *locationService;
@property(nonatomic,copy) NSString *phone;
@property(nonatomic,copy) NSString *token;
@property(nonatomic,strong) NSArray *postman;//快递员位置


@property(nonatomic,strong) UIView *cover;
@property(nonatomic,strong) UIView *coverview;//go 的界面


//录音按钮相关
//点击录音按钮蒙板显示
@property(nonatomic,strong) UIView * recorderBGView;
//录音按钮当前状态
@property(nonatomic,assign) BOOL isRecorderWorking;
@property(nonatomic,strong) UIButton * cancelButton;//取消录音按钮
@property(nonatomic,strong) UIButton * playButton;//播放录音按钮


@property (nonatomic, strong) MLAudioRecorder * recorder;
@property (nonatomic, strong) AmrRecordWriter * amrWriter;

@property (nonatomic, strong) MLAudioPlayer * player;
@property (nonatomic, strong) AmrPlayerReader * amrReader;

@property (nonatomic, strong) AVAudioPlayer * avAudioPlayer;

@property (nonatomic, copy) NSString * filePath;
@property (nonatomic, strong) MLAudioMeterObserver * meterObserver;

@property (nonatomic, retain) UIImageView * circleImageView;//圈圈图片
@property (nonatomic, retain) UIImageView * voiceAnimationView;//语音图片

@property (nonatomic, retain) UILabel * labelTop;//录音时显示的文字
@property (nonatomic, retain) UILabel * labelMid;//录音时显示的文字
@property (nonatomic, retain) UILabel * labelDown;//录音时显示的文字
@property (nonatomic, retain) UILabel * voiceDown;//录音时显示的文字

@property (nonatomic, assign) BOOL uploadSuccess;

@end


@implementation CQViewController

//按钮标识
static bool local = NO;
static int  flag = 0;

/**
 *  懒加载
 */
-(NSArray *)postman
{
    if (_postman ==nil)
    {
        _postman = [NSArray array];
    }
    return  _postman;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        [self setUpMap];
    });
    
    
    //订阅登录成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logined:) name:@"LOGINED" object:nil];
    [self.view setBackgroundColor: [UIColor grayColor]];
    
    //--------------------------sql text------------------------------//
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
    
    
    // 2.得到数据库
    FMDatabase *db = [FMDatabase databaseWithPath:filename];
    if([db open])
    {
        
        FMResultSet *resultset =  [db executeQuery:@"select * from userinfo"];
        while ([resultset next]) {
            NSString *token = [resultset stringForColumn:@"token"];
            
           
            
            self.token = token;
        }
        
    }
    //--------------------------sql end------------------------------//
    //"有件快递"标题
    //self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn_yjkd"]];
    self.navigationItem.title = @"有件快递";
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;

    
    if (self.token == nil)//未登录
    {
                self.isLogin = NO;
        
        //添加一个有件快递按钮
        UIButton *youjian =  [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 69, 17)];
        [youjian setTitle:@"有件快递" forState:UIControlStateNormal];
        [youjian setTitleColor:[UIColor redColor] forState: UIControlStateNormal];
        
        [youjian setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
        
        youjian.userInteractionEnabled = NO;

        self.navigationItem.titleView = youjian;
        
        
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"order_normal" highImageName:@"order_normal" target:self action:@selector(login)];
        self.navigationItem.rightBarButtonItem = nil;
        

    }
    else//已登录
    {
        
        
        self.isLogin = YES;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(signout) name:@"SIGNOUT" object:nil];
       

        //添加一个有件快递按钮
        UIButton *youjian =  [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 69, 17)];
        [youjian setTitle:@"有件快递" forState:UIControlStateNormal];
        [youjian setTitleColor:[UIColor redColor] forState: UIControlStateNormal];
        
        [youjian setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];

        youjian.userInteractionEnabled = NO;
        
        self.navigationItem.titleView=youjian;
        self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"person_normal" highImageName:@"person_normal" target:self action:@selector(function)];
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"order_normal" highImageName:@"order_normal" target:self action:@selector(rightClick)];
        
        
        
        
        [self recorderControl];
        
        
        
        
        
        //添加阴影效果
        UIImageView *shaddleview = [[UIImageView alloc] initWithFrame:CGRectMake(-1, 0, 1, HMScreenH)];
        [shaddleview setImage:[UIImage imageNamed:@"shaddle_v"]];
        [self.view addSubview:shaddleview];
        
        
        //添加一个通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(rightClick) name:XJZF object:nil];

        
    }
    //uuid
    //NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    //    HMLog(@"udid is %@",[defaults objectForKey:@"SHOPEN_UDID"]);
}

-(void)sendAddress:(NSString *)address
{
    
    
    //    NSString *str=[NSString stringWithFormat:@"http://api.map.baidu.com/geocoder?output=json&location=39.983424,%20116.322987&key=ye9PrtTD0DSPRgLvXaoXNHWk",self.longitude];
    //
    //    NSString *stringurl =  [@"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //     NSURL *url = [NSURL URLWithString:stringurl];
    //
    //
    //    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    //    request.timeOutSeconds = 10;
    //    // 2.发送请求
    //    [request startSynchronous];
    //    // 3.检测服务器返回的结果
    //    if (request.error) { // 请求出错(比如超时)
    //        HMLog(@"请求出错---%@", request.error);
    //    } else { // 请求成功
    //        HMLog(@"%d %@", request.responseStatusCode, request.responseStatusMessage);
    //        //        HMLog(@"%d", request.responseData.length);
    //        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableLeaves error:nil];
    //        HMLog(@"%@", dict);
    //        HMLog(@"%@", request.responseString);
    //    }
    
}


/**
 *  点击右侧按钮 (我的)
 */
-(void)rightClick
{
    SHTableViewController *controller = [[SHTableViewController alloc] init];
    [self.navigationController pushViewController:controller animated:YES];
}
/**
 *  初始化地图
 */
-(void)setUpMap
{
    //IOS8适配
    if(IOS8)
    {
        HMLog(@"ios8");
        locationManager = [[CLLocationManager alloc] init];
        [locationManager requestAlwaysAuthorization];
        [locationManager startUpdatingLocation];

    }

    
    self.manager = [[BMKMapManager alloc] init];
    [self.manager start:BDAPI generalDelegate:self];
    //添加定位服务代理
    self.locationService = [[BMKLocationService alloc] init];
    self.locationService.delegate = self;
    
    //添加地图代理
    BMKMapView *map = [[BMKMapView alloc] init];
    self.mapview  = map;
    self.mapview.zoomLevel = 17;
    map.frame = [UIScreen mainScreen].bounds;
    
    [self.view addSubview: map];
    
    //添加mapview的代理
    self.mapview .delegate = self;
    
    self.mapview.showsUserLocation = NO;
    self.mapview.userTrackingMode = BMKUserTrackingModeFollow;
    self.mapview.showsUserLocation = YES;
    
    
}
/**
 *  点击退出登录
 */
-(void)signout
{
    //1.关闭抽屉
    self.phone = nil;
    //没有蒙版直接执行动画 关闭抽屉
    if(self.cover == nil)
    {
        [UIView animateWithDuration:0.5 animations:^{
            self.navigationController.view.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            
        }];
    }
    //有蒙版的话就点击蒙版
    else
    {
        [self coverClick:self.cover];
    }
    //1.1将flag=1;说明是退出登录过去的
    flag = 1;
    
    self.token = nil;
    //2.重新刷新界面
    [self viewDidLoad];
    
}
-(void)logined:(NSNotification *)note
{
    self.isLogin = YES;
    [self viewDidLoad];
    //提示登录成功
    
    MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.labelText =@"登录成功";
    HUD.mode = MBProgressHUDModeText;
    
    [HUD showAnimated:YES whileExecutingBlock:^{
        sleep(1.5);
    } completionBlock:^{
        [HUD removeFromSuperview];
    }];

    
}

/**
 *  添加返回按钮
 */
-(void)addreturnButton
{
    UIButton *button  = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 40, 20)];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button addTarget: self  action:@selector(begin) forControlEvents:UIControlEventTouchUpInside];
    button .hidden = YES;
    [self.view addSubview:button];
}

/**
 *  点击跳转到登录页面
 */
-(void)login
{
    SHLogin *login = [[SHLogin alloc] init];
    UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:login];
    
    [self presentViewController:nv animated:YES completion:^{
        
        HMLog(@"登录视图已经弹出");
        
    }];
}

-(void)viewWillAppear:(BOOL)animated
{
    
    //添加回归按钮
    
    UIButton *button2  = [[UIButton alloc] initWithFrame:CGRectMake(HMScreenW -50, HMScreenH-15-29-12, 24, 24)];
    [button2 setImage:[UIImage imageNamed:@"icon_position"] forState:UIControlStateNormal];
    [button2 addTarget: self  action:@selector(begin) forControlEvents:UIControlEventTouchUpInside];
    button2.hidden = YES;
    self.returnBtn = button2;
    
    UIButton *btnmac  = [[UIButton alloc] initWithFrame:SHRectMakeRound(HMScreenW/2-29, HMScreenH-15-57, 57, 57)];
    [btnmac setImage:[UIImage imageNamed:@"create_order_normal"] forState:UIControlStateNormal];
    [btnmac addTarget: self  action:@selector(setVoice:) forControlEvents:UIControlEventTouchUpInside];
    self.btnmac = btnmac;
    
    
    //给录音按钮添加长按手势
    UILongPressGestureRecognizer * longPressTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressTapClick:)];
    longPressTap.minimumPressDuration = 0.4f;
    longPressTap.delegate = self;
    [btnmac addGestureRecognizer:longPressTap];
    
    
    
    //给录音按钮添加移动手势
    UIPanGestureRecognizer * panMoveTap = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panMoveTapClick:)];
    panMoveTap.delegate = self;
    [btnmac addGestureRecognizer:panMoveTap];
    
    
    
    //将按钮添加到view上
    [self.view addSubview:button2];
    [self.view addSubview:btnmac];
    
    
    //自动调用 开始定位
    [self begin];
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //添加navigationCell
        UIView *view = [[NSBundle mainBundle] loadNibNamed:@"NavigationCell" owner:self options:nil][0];
        view.frame= CGRectMake(0, 69, 320, 30);
        
        [self.buttonCover addTarget:self action:@selector(clickCellCover) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview: view];
        
    });
    
}

-(void)paymentResultDelegate:(NSString *)result
{
    HMLog(@"%@",result);
}



#pragma mark -点击顶部导航cell
/**
 *  点击顶部导航cell
 *
 */
-(void)clickCellCover
{
    
    SHSearch2ViewController *guide = [[SHSearch2ViewController alloc] init];
        guide.celltext = self.buttonCover;
    guide.latitude = self.latitude;
    guide.longitude = self.longitude;
    [self.navigationController pushViewController:guide animated:YES];
}

/**
 *  点击左侧图片
 */
-(void)function
{
   
    
    [UIView animateWithDuration:0.5 animations:^{
        if (CGAffineTransformIsIdentity( self.navigationController .view.transform))
        {
            self.navigationController .view.transform = CGAffineTransformTranslate(self.navigationController.view.transform, 260, 0);
            
            // 添加一个遮盖
            UIButton *cover = [[UIButton alloc] init];
            cover.tag = 1;
            [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
            cover.frame = self.navigationController.view.bounds;
            self.cover = cover ;
            [self.navigationController.view addSubview:cover];
            
        }
        else
        {
            self.navigationController .view.transform =CGAffineTransformIdentity;//回复
        }
    }];
    
    
}

/**
 *  点击蒙版
 *
 */
- (void)coverClick:(UIView *)cover
{
    [UIView animateWithDuration:0.5 animations:^{
        self.navigationController.view.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        
        [cover removeFromSuperview];
    }];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
    
    
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

/**
 *  开始定位
 */
-(void)begin
{
    

    
    
    
    [self.locationService startUserLocationService];
    self.mapview.showsUserLocation = NO;//先关闭显示的定位图层
    self.mapview.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    self.mapview.userTrackingMode = BMKUserTrackingModeFollow;
    self.mapview.showsUserLocation = YES;//显示定位图层
    self.mapview.showMapScaleBar = YES;
    self.returnBtn.hidden  = YES;
    
    
    
    
}

/**
 *  点击发送语音按钮
 */
-(void)setVoice:(UIButton *)singleTapRecorder
{
    if (self.isLogin)
    {
        
        if (singleTapRecorder.tag == ButtonTagRecorder) {
            HMLog(@"点击发送语音按钮 recorder~");
//            UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HMScreenW, HMScreenH)];
//            view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"mask_bg_view"]];
//            view.tag = 567890;
//            [[[UIApplication sharedApplication] keyWindow] addSubview:view];
//            
//            SHRedPacketUseView * views = [[SHRedPacketUseView alloc] initWithFrame:SHRectMake(25, 120, 270, HMScreenH - 120 - 286)];
//            views.backgroundColor = [SHUtilitiesTool colorWithHexString:@"#f7f7f7"];
//            views.layer.cornerRadius = 6;
//            [view addSubview:views];
            
//            SHComplaintsView * views = [[SHComplaintsView alloc] init];
//            views.tokenStr = @"";
//            views.deliverId = @"";
//            views.delegate = self;
//            views.frame = SHRectMake(20, 84, HMScreenW -40, HMScreenH - 168);
//            views.backgroundColor = [SHUtilitiesTool colorWithHexString:@"#f7f7f7"];
//            views.layer.cornerRadius = 6;
//            //views.alpha = 1.0;
//            [view addSubview:views];
            
            [ToastView showToastViewWithContent:@"亲，长按才可以录音哦" andRect:CGRectMake(100,200,120,80) andTime:2.0f andObject:self];
        }
        else if (singleTapRecorder.tag == ButtonTagGo){
            HMLog(@"点击发送语音按钮 go~");
            //存放图片的文件夹
            [self.btnmac setImage:[UIImage imageNamed:@"btn_go_press"] forState:UIControlStateNormal];
            [self upload];
            
        }
        HMLog(@"点击发送语音按钮");
        
        
    }
    else
    {
        [MBProgressHUD showSuccess:@"请登录"];
    }
    
    
    
}

-(void)removeComplaintView{
    UIView * view = (UIView *)[[[UIApplication sharedApplication] keyWindow] viewWithTag:567890];
    [view removeFromSuperview];
}

/*
 
 *  语音上传服务器
 
 */
-(void)upload{
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@uploader",SHAPIURL_VOICE_B]]];
    [request setFile:self.amrWriter.filePath  forKey:@"amr"];
//    [request setUploadProgressDelegate:self];
//    [request showAccurateProgress];
    [request setDelegate:self];
    [request startAsynchronous];
}
//上传进度
//-(void)setProgress:(float)newProgress{
//    
//    HMLog(@"上传的百分比进度为 %f",newProgress);
//}

- (void)requestFailed:(ASIHTTPRequest *)request {
    HMLog(@"请求失败");
    [ToastView showToastViewWithContent:@"上传语音失败" andRect:SHRectMake(100,200,120,80) andTime:2.0f andObject:self];
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    HMLog(@"%@",request);
    //[ToastView showToastViewWithContent:@"上传语音" andRect:SHRectMake(100,200,120,80) andTime:2.0f andObject:self];
    HMLog(@"self.amrwriteamr is %@",self.amrWriter.filePath);
    NSArray * array = [self.amrWriter.filePath componentsSeparatedByString:@"/"];
    NSString * audioName = [array lastObject];
    HMLog(@"audioName is %@",audioName);
    HMLog(@"token is %@",self.token);
    NSString * sendAddress = [[self.buttonCover.titleLabel.text componentsSeparatedByString:@" "] lastObject];
    NSDictionary *dic = @{@"duration":[NSString stringWithFormat:@"%d", self.currentRecorderTime/2 +1],@"longitude":[NSString stringWithFormat:@"%f",self.longitude],@"latitude":[NSString stringWithFormat:@"%f",self.latitude],@"sendAddress":sendAddress,@"token":self.token,@"audioName":audioName};
    
    
    [SHHTTPTOOL PostOrderWithDic:dic andAction:@"userCreateOrder" success:^(id responseObj) {
        NSDictionary * dict = [SHUtilitiesTool dictionaryWithJsonString:responseObj];
        HMLog(@"%@************dict ",dict);
        NSDictionary * dict2 = dict[@"msg"];
       
        NSString * send = [dict2 objectForKey:@"sended"];
        NSString * orderId = [dict2 objectForKey:@"orderId"];
        self.recieveNumber = [send intValue];
        if ([send intValue] >= 0) {
            self.recorderBGView.hidden = YES;
            SHSearchAnimationViewController * controller = [[SHSearchAnimationViewController alloc] init];
            controller.delegate = self;
            controller.orderId = orderId;
            controller.currentVoiceSendCount = [send integerValue];;
            controller.tokenKey = self.token;
            UINavigationController * nav = [[UINavigationController alloc]
                                            initWithRootViewController:controller];
            [self.navigationController presentViewController:nav animated:YES completion:^{
                
            }];
        }
    } failure:^(NSError *error) {
        HMLog(@"失败");
        [ToastView showToastViewWithContent:@"新建订单失败" andRect:SHRectMake(100,200,120,80) andTime:2.0f andObject:self];
    }];
}



// 从Docment目录获取文件，文件格式取决于传进的参数
-(NSMutableArray *)getAllFileOfFileType:(NSString *)type{
    NSFileManager *fileManager = [[NSFileManager defaultManager] init] ;
    NSMutableArray * everyTitle = [[NSMutableArray alloc] init];
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *filePath = [filePaths objectAtIndex:0];
    NSDirectoryEnumerator *direnum = [fileManager enumeratorAtPath:filePath];
    
    NSString *fileName = nil;
    NSMutableArray * arrayFile = [[NSMutableArray alloc] initWithCapacity:10];
    
    while ((fileName = [direnum nextObject])) {
        if([[fileName pathExtension] isEqualToString:type]){
            [arrayFile addObject:fileName];
            NSArray *strings = [fileName componentsSeparatedByString:@"."];
            NSString *fileTitle = [strings objectAtIndex:[strings count]-2];
            [everyTitle addObject:fileTitle];
        }
    }
    HMLog(@"%@", arrayFile);
    return arrayFile;
}

/**
 *  添加大头针
 */
- (void)addPointAnnotation:(double )latitude  longitude:(double)longitude
{
    BMKPointAnnotation *pointAnnotation = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coor;
    coor.latitude = latitude;
    coor.longitude = longitude;
    pointAnnotation.coordinate = coor;
    [self.mapview addAnnotation:pointAnnotation];
    
    
}

#pragma mark -BMKGeneralDelegate
/**
 *返回网络错误
 *@param iError 错误号
 */
- (void)onGetNetworkState:(int)iError
{
    
    if (iError == 0)
    {
        HMLog(@"lianwang ok");
        
    }
}


/**
 *返回授权验证错误
 *@param iError 错误号 : BMKErrorPermissionCheckFailure 验证失败
 */
- (void)onGetPermissionState:(int)iError
{
    if (iError == 0)
    {
       
    }
    
}

/**
 *在将要启动定位时，会调用此函数
 */
- (void)willStartLocatingUser
{
    
}

/**
 *在停止定位后，会调用此函数
 */
- (void)didStopLocatingUser
{
 
}

- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    
    [self.mapview updateLocationData:userLocation];
    
    
    
    
    if(local ==NO)
    {
        
        HMLog(@"纬度:%f--精度:%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        NSString *latitude = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude];
        NSString *longitude = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude];
        self.latitude = userLocation.location.coordinate.latitude;
        self.longitude = userLocation.location.coordinate.longitude;
        //定位
        [self sendLocationwithjing:self.longitude andwei:self.latitude];
        //发送 经纬度
        //返回快递员经纬度
        //获取经纬度之后立刻添加到地图上
        
        NSDictionary *dic = @{@"longitude":longitude,@"latitude":latitude};
        [SHHTTPTOOL PostWithDic:dic andAction:@"userGetExpressor" success:^(id responseObj) {
            NSDictionary *dic = responseObj[@"msg"];
            NSArray *list = dic[@"list"];
            self.postman = list;
            
            
            
            int postmancount = self.postman.count;
            if (postmancount >0)
            {
                
                MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HUD];
                HUD.labelText =[NSString stringWithFormat:@"附近有%d位快递员为您服务",self.postman.count];
                HUD.mode = MBProgressHUDModeText;
                
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1.5);
                } completionBlock:^{
                    [HUD removeFromSuperview];
                }];
            }
            else
            {
                MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HUD];
                HUD.labelText =@"附近没有快递员";
                HUD.mode = MBProgressHUDModeText;
                
                
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1.5);
                } completionBlock:^{
                    [HUD removeFromSuperview];
                }];
            }
            for (int i =0;i<self.postman.count;i++)
            {
                
                NSDictionary *dic =  (NSDictionary *)self.postman[i];
                
                [self addPointAnnotation:[dic[@"latitude"] doubleValue] longitude:[dic[@"longitude"] doubleValue]];
            }
            
            
            
        } failure:^(NSError *error) {
            
        }];
    }
    local = YES;
}

#pragma mark -定位
-(void)sendLocationwithjing:(double)jing andwei:(double)wei
{
    NSString *location = [NSString stringWithFormat:@"&location=%f,",wei];
    
    NSString *location2 = [NSString stringWithFormat:@"%f",jing];
    NSString *str=[NSString stringWithFormat:@"http://api.map.baidu.com/geocoder?output=json%@%@&key=%@",location,location2,BDAPI];
    
    
    NSString *stringurl = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:stringurl];
    
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    request.timeOutSeconds = 10;
    // 2.发送请求
    [request startSynchronous];
    // 3.检测服务器返回的结果
    if (request.error) { // 请求出错(比如超时)
        HMLog(@"请求出错---%@", request.error);
    } else {
        // 请求成功
        //HMLog(@"%d %@", request.responseStatusCode, request.responseStatusMessage);
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:request.responseData options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *result = (NSDictionary *) dict[@"result"];
        
        
        HMLog(@"%@",result[@"formatted_address"]);
        [self.buttonCover setTitle:[NSString stringWithFormat:@"我在 %@", result[@"formatted_address"]] forState:UIControlStateNormal];
    }
}

#pragma mark -mapViewDelegate
/**
 *  当显示区域改变时候
 */
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    self.returnBtn.hidden = NO;
    
}
/**
 *  替换大头针
 *
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        
        
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        
        newAnnotationView.annotation=annotation;
        
        newAnnotationView.image = [UIImage imageNamed:@"Locationicon"];
        return newAnnotationView;
        
    }
    return  nil;
    
}

#pragma mark - voice abount
//录音相关控件实例化
-(void)recorderControl{
    //获取路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    AmrRecordWriter *amrWriter = [[AmrRecordWriter alloc]init];
    amrWriter.filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.amr",[SHUtilitiesTool UUIDString]]];
    amrWriter.maxSecondCount = 60;
    amrWriter.maxFileSize = 1024*256;
    self.amrWriter = amrWriter;
    
    //此处首先指定了图片存取路径（默认写到应用程序沙盒 中)
    
    
    
    
    //    if([self isExistsFile:amrWriter.filePath]){
    //        data=[NSData dataWithContentsOfFile:amrWriter.filePath];
    //    }else{
    //        data = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"http://211.154.154.96:7071/press/163/songzi/0.jpg"]];
    //
    //        //创建文件夹路径
    //        [[NSFileManager defaultManager] createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:nil];
    //
    //        //创建图片
    //        [UIImagePNGRepresentation([UIImage imageWithData:data]) writeToFile:imagePath atomically:YES];
    //    }
    //    imageView.image = [UIImage imageWithData:data];
    
    MLAudioMeterObserver *meterObserver = [[MLAudioMeterObserver alloc]init];
    meterObserver.actionBlock = ^(NSArray *levelMeterStates,MLAudioMeterObserver *meterObserver){
        //DLOG(@"volume:%f",[MLAudioMeterObserver volumeForLevelMeterStates:levelMeterStates]);
    };
    meterObserver.errorBlock = ^(NSError *error,MLAudioMeterObserver *meterObserver){
        [self AlertViewWarning:error.userInfo[NSLocalizedDescriptionKey]];
    };
    self.meterObserver = meterObserver;
    //录音初始化
    MLAudioRecorder *recorder = [[MLAudioRecorder alloc]init];
    __weak __typeof(self)weakSelf = self;
    recorder.receiveStoppedBlock = ^{
        //[weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;
    };
    recorder.receiveErrorBlock = ^(NSError *error){
        //[weakSelf.recordButton setTitle:@"Record" forState:UIControlStateNormal];
        weakSelf.meterObserver.audioQueue = nil;
        [self AlertViewWarning:error.userInfo[NSLocalizedDescriptionKey]];
    };
    
    
    //caf
    //    recorder.fileWriterDelegate = writer;
    //    self.filePath = writer.filePath;
    //mp3
    //    recorder.fileWriterDelegate = mp3Writer;
    //    self.filePath = mp3Writer.filePath;
    
    //amr
    recorder.bufferDurationSeconds = 0.5;
    recorder.fileWriterDelegate = self.amrWriter;
    
    self.recorder = recorder;
    
    //播放器初始化
    //*************************************************
    MLAudioPlayer *player = [[MLAudioPlayer alloc]init];
    AmrPlayerReader *amrReader = [[AmrPlayerReader alloc]init];
    
    player.fileReaderDelegate = amrReader;
    player.receiveErrorBlock = ^(NSError *error){
        //[weakSelf.playButton setTitle:@"Play" forState:UIControlStateNormal];
        [self AlertViewWarning:error.userInfo[NSLocalizedDescriptionKey]];
    };
    player.receiveStoppedBlock = ^{
        //[weakSelf.playButton setTitle:@"Play" forState:UIControlStateNormal];
    };
    self.player = player;
    self.amrReader = amrReader;
    
    
    
}

-(void)AlertViewWarning:(NSString *) string{
    if (IOS7) {
        //iOS7用alertView
        [[[UIAlertView alloc]initWithTitle:@"错误" message:string delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil] show];
    }else if (IOS8){
        //iOS8用alertController
        //*    1
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"语音发生错误" message:string preferredStyle:UIAlertControllerStyleAlert];
        //*    2
        //*    3
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        
        //*    4
        // Add the actions.
        [alert addAction:otherAction];
        //*    5
        [self presentViewController:alert animated:YES completion:nil];
    }
}

//录音按钮长按手势响应事件、移动手势响应事件
-(void)longPressTapClick:(UILongPressGestureRecognizer *)longPress{
    CGPoint pt = [longPress locationInView:self.view];
    //CGPoint midValue = pt;
    if (longPress.view.tag == ButtonTagRecorder) {
        if (longPress.state == UIGestureRecognizerStateBegan) {
            [self creatVoiceBGView];
            [self.btnmac setImage:[UIImage imageNamed:@"btn_go_press"] forState:UIControlStateNormal];
            [self.recorder startRecording];
            self.currentRecorderTime = 0;
            self.recorderVoiceTimer = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(countTime) userInfo:nil repeats:YES];
            if (_isRecorderWorking == NO) {
                [UIView animateWithDuration:1.0f animations:^{
                    _isRecorderWorking = YES;
                    [self.recorderBGView setBackgroundColor:[UIColor whiteColor]];
                } completion:^(BOOL finished) {
                    
                }];
            }
        }else if(longPress.state == UIGestureRecognizerStateEnded || longPress.state == UIGestureRecognizerStateFailed || longPress.state == UIGestureRecognizerStateCancelled){
            self.cancelButton.hidden = NO;
            self.btnmac.tag = ButtonTagGo;
            if (pt.y > (float)HMScreenH/480*430) {
                [self.btnmac setImage:[UIImage imageNamed:@"btn_go"] forState:UIControlStateNormal];
            }
            //手势结束注销计时器 停止录音
            [self.recorderVoiceTimer invalidate];
            self.recorderVoiceTimer = nil;
            [self.recorder stopRecording];
            self.playButton.hidden = NO;
            self.voiceAnimationView.hidden = YES;
            self.circleImageView.hidden = YES;
            self.labelMid.hidden = YES;
            self.labelDown.hidden = YES;
            self.labelTop.hidden = YES;
            self.voiceDown.text = @"听听效果如何";
        }
    }
}
//录音计时
- (void)countTime{
    self.currentRecorderTime += 1;
    NSLog(@"当前录音是多少秒 %d",self.currentRecorderTime);
    int voiceTimer;
    voiceTimer = self.currentRecorderTime %3;
    if(self.currentRecorderTime % 2 == 1){
        [UIView animateWithDuration:1.0f animations:^{
            [self.circleImageView setFrame:SHRectMakeRound(CIRCLE_OX - 42, CIRCLE_OY - 42, CIRCLE_S + 84, CIRCLE_S + 84)];
        } completion:^(BOOL finished) {
            [self.circleImageView setFrame:SHRectMakeRound(110, 138 + NOT_FOR_IOS7, 100, 100)];
        }];
    }
    if (self.currentRecorderTime > 10) {
        self.labelTop.text = @"松开按钮可以结束录音";
        self.labelMid.hidden = YES;
        self.labelDown.hidden = YES;
    }
    if (self.currentRecorderTime >= 30) {
        switch ((self.currentRecorderTime - 30) / 2) {
            case 0:
                self.labelTop.text = @"还能录5秒";
                break;
            case 1:
                self.labelTop.text = @"还能录4秒";
                break;
            case 2:
                self.labelTop.text = @"还能录3秒";
                break;
            case 3:
                self.labelTop.text = @"还能录2秒";
                break;
            case 4:
                self.labelTop.text = @"还能录1秒";
                break;
            default:
                break;
        }
    }
    if (self.currentRecorderTime <40) {
        return;
    }
    if (self.currentRecorderTime == 40) {
        self.labelTop.hidden = YES;
        self.voiceDown.text = @"听听效果如何";
        [self.recorderVoiceTimer invalidate];
        self.recorderVoiceTimer = nil;
    }
}

-(void)panMoveTapClick:(UIPanGestureRecognizer *)panPress{

    CGPoint pt = [panPress locationInView:self.view];
    if (pt.y < (float)HMScreenH/480 * 430.0f) {
        [self.voiceAnimationView setImage:[UIImage imageNamed:@"record_cancel"]];
        self.labelTop.hidden = YES;
        self.labelMid.hidden = YES;
        self.labelDown.hidden = YES;
        _isRecorderWorking = NO;
        self.voiceDown.text = @"松开手指 取消录音";
    }else if(pt.y > (float)HMScreenH/480 * 450.0f){
        self.voiceDown.text = @"手指上滑 取消发送";
        self.labelTop.hidden = NO;
        [self.voiceAnimationView setImage:[UIImage imageNamed:@"recording"]];
        if (self.currentRecorderTime <= 10) {
            self.labelTop.hidden = NO;
            self.labelMid.hidden = NO;
            self.labelDown.hidden = NO;
        }
        if (self.currentRecorderTime > 10 && self.currentRecorderTime < 30) {
            self.labelTop.text = @"松开按钮可以结束录音";
            self.labelMid.hidden = YES;
            self.labelDown.hidden = YES;
        }
        if (self.currentRecorderTime >=30 && self.currentRecorderTime < 40) {
            switch ((self.currentRecorderTime - 30) / 2) {
                case 0:
                    self.labelTop.text = @"还能录5秒";
                    break;
                case 1:
                    self.labelTop.text = @"还能录4秒";
                    break;
                case 2:
                    self.labelTop.text = @"还能录3秒";
                    break;
                case 3:
                    self.labelTop.text = @"还能录2秒";
                    break;
                case 4:
                    self.labelTop.text = @"还能录1秒";
                    break;
                default:
                    break;
            }
        }
        if (self.currentRecorderTime < 40) {
            return;
        }
        if (self.currentRecorderTime == 40) {
            self.labelTop.hidden = YES;
            self.voiceDown.text = @"听听效果如何";
            [self.recorderVoiceTimer invalidate];
            self.recorderVoiceTimer = nil;
        }
    }
    if (panPress.state == UIGestureRecognizerStateEnded || panPress.state == UIGestureRecognizerStateFailed || panPress.state == UIGestureRecognizerStateCancelled) {
        if (pt.y < (float)HMScreenH/480 * 430) {
            [self.recorderVoiceTimer invalidate];
            self.recorderVoiceTimer = nil;
            self.recorderBGView.hidden = YES;
            _isRecorderWorking = NO;
            self.btnmac.tag = ButtonTagRecorder;
            [self.btnmac setImage:[UIImage imageNamed:@"create_order_normal"] forState:UIControlStateNormal];
        }else{
            self.labelTop.hidden = YES;
            self.voiceDown.text = @"听听效果如何";
        }
    }
    HMLog(@"***********%f",pt.y);
}

//为了可以同时触发两个手势
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

//创建蒙板View
-(void)creatVoiceBGView{
    UIView * view = [[UIView alloc] init];
    self.coverview = view;
    view.frame = CGRectMake(0, 0, HMScreenW , HMScreenH);
    view.backgroundColor = [UIColor clearColor];
    //view.backgroundColor = [UIColor colorWithRed:0.6 green:0.4 blue:0.5 alpha:0];
    self.recorderBGView = view;
    [self.view addSubview:self.recorderBGView];
    
    [self.view bringSubviewToFront:self.btnmac];
    
    [self cancelRecorderButton];
    [self creatPlayButton];
    [self creatRecordVoiceImageView];
    [self creatVoiceLabel];
}
//取消录音按钮
-(void)cancelRecorderButton{
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = SHRectMakeRound(self.btnmac.frame.origin.x - 90, self.btnmac.frame.origin.y + 10, 30, 30);
    [btn setImage:[UIImage imageNamed:@"btn_voice_cancel_default"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    btn.hidden = YES;
    btn.tag = ButtonTagCancel;
    self.cancelButton = btn;
    [self.recorderBGView addSubview:self.cancelButton];
}
/*
 
 * 添加播放声音按钮
 
 */
-(void)creatPlayButton{
    UIButton * voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceBtn setBackgroundImage:[UIImage imageNamed:@"record_voice_playin_replace_3"] forState:UIControlStateNormal];
    [voiceBtn addTarget:self action:@selector(playClick:) forControlEvents:UIControlEventTouchUpInside];
    voiceBtn.hidden = YES;
    voiceBtn.frame = SHRectMakeRound(110, 138 + NOT_FOR_IOS7, 100, 100);
    self.playButton = voiceBtn;
    self.playButton.hidden = YES;
    [self.recorderBGView addSubview: self.playButton];
}
//取消按钮点击事件
-(void)cancelBtnClick{
    [self.recorderBGView removeFromSuperview];
    _isRecorderWorking = NO;
    [self.btnmac setImage:[UIImage imageNamed:@"create_order_normal"] forState:UIControlStateNormal];
    self.btnmac.tag = ButtonTagRecorder;
}

//-(void)disPlayToastView{
//    [ToastView showToastViewWithContent:@"亲，你的小纸条已经成功汇报到班主任那里了" andRect:CGRectMake(100,200,120,80) andTime:2.0f andObject:self];
//}
//recorderBGView上面显示文字
-(void)creatVoiceLabel{
    UILabel * label = [[UILabel alloc] initWithFrame:SHRectMake(0, 40 + NOT_FOR_IOS7, HMScreenW, 18)];
    label.font = [UIFont systemFontOfSize:17.0f];
    label.adjustsFontSizeToFitWidth = YES;
    label.backgroundColor = [UIColor clearColor];
    label.text = @"你可以这样说";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [SHUtilitiesTool colorWithHexString:@"#666666"];
    self.labelTop = label;
    [self.recorderBGView addSubview:self.labelTop];
    
    UILabel * label1 = [[UILabel alloc] initWithFrame:SHRectMake(0, label.frame.origin.y + label.frame.size.height + 14, HMScreenW, 15)];
    label1.font = [UIFont systemFontOfSize:14.0f];
    label1.adjustsFontSizeToFitWidth = YES;
    label1.backgroundColor = [UIColor clearColor];
    label1.text = @"我在小关北里渔阳置业大厦B座504";
    label1.textAlignment = NSTextAlignmentCenter;
    label1.textColor = [SHUtilitiesTool colorWithHexString:@"#666666"];
    self.labelMid = label1;
    [self.recorderBGView addSubview:self.labelMid];
    
    UILabel * label2 = [[UILabel alloc] initWithFrame:SHRectMake(0, label1.frame.origin.y + label1.frame.size.height + 9, HMScreenW, 15)];
    label2.font = [UIFont systemFontOfSize:14.0f];
    label2.adjustsFontSizeToFitWidth = YES;
    label2.backgroundColor = [UIColor clearColor];
    label2.text = @"有件快递到上海";
    label2.textAlignment = NSTextAlignmentCenter;
    label2.textColor = [SHUtilitiesTool colorWithHexString:@"#666666"];
    self.labelDown = label2;
    [self.recorderBGView addSubview:self.labelDown];
    
    UILabel * label3 = [[UILabel alloc] initWithFrame:SHRectMake(0, 247 + NOT_FOR_IOS7, HMScreenW, 13)];
    label3.font = [UIFont systemFontOfSize:12.0f];
    label3.adjustsFontSizeToFitWidth = YES;
    label3.backgroundColor = [UIColor clearColor];
    label3.text = @"手指上滑 取消发送";
    label3.textAlignment = NSTextAlignmentCenter;
    label3.textColor = [SHUtilitiesTool colorWithHexString:@"#999999"];
    self.voiceDown = label3;
    [self.recorderBGView addSubview:self.voiceDown];
}
/*
 
 * 录音动画效果
 
 */
-(void)creatRecordVoiceImageView{
    UIImageView * view = [[UIImageView alloc] initWithFrame:SHRectMakeRound(110, 138 + NOT_FOR_IOS7, 100, 100)];
    view.image = [UIImage imageNamed:@"recording"];
    self.voiceAnimationView = view;
    [self.recorderBGView addSubview:view];
    
    UIImageView * circleView = [[UIImageView alloc] initWithFrame:SHRectMakeRound(110, 138 + NOT_FOR_IOS7, 100, 100)];
    circleView.image = [UIImage imageNamed:@"record_voice_circle"];
    self.circleImageView = circleView;
    [self.recorderBGView addSubview:self.circleImageView];
}
/*
 
 重播声音按钮，动画由计时器实现
 
 */
-(void)playClick:(UIButton *)playBtn {
    HMLog(@"filePath 文件所在位置为 %@",self.amrWriter.filePath);
    self.amrReader.filePath = self.amrWriter.filePath;
    //DLOG(@"文件时长%f",[AmrPlayerReader durationOfAmrFilePath:self.amrReader.filePath]);
    HMLog(@"******************filepath is %@",self.amrReader.filePath);
    if (self.player.isPlaying) {
        [self.player stopPlaying];
        [self.playVoiceTimer invalidate];
        self.playVoiceTimer = nil;
        self.currentPlayTime = 0;
    }else{
        [self.player startPlaying];
        if (self.currentRecorderTime > 0) {
            [self.playVoiceTimer invalidate];
            self.playVoiceTimer = nil;
            self.currentPlayTime = 0;
            self.playVoiceTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(playVoiceCount) userInfo:nil repeats:YES];
        }
    }
}
/*
 
 计时器方法实现播放声音效果
 
 */
-(void)playVoiceCount{
    //根据计时器调整播放按钮的图片
    self.currentPlayTime ++;
    if (self.currentPlayTime < self.currentRecorderTime/2) {
        int picNow;
        switch (self.currentPlayTime % 3) {
            case 0:
                picNow = 3;
                break;
            case 1:
                picNow = 1;
                break;
            case 2:
                picNow = 2;
                break;
            default:
                break;
        }
        UIButton * btn = (UIButton *)self.playButton;
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"record_voice_playin_replace_%d",picNow]] forState:UIControlStateNormal];
        
    }else{
        //录音结束恢复原本图片
        UIButton * btn = (UIButton *)self.playButton;
        [btn setBackgroundImage:[UIImage imageNamed:@"record_voice_playin_replace_3"] forState:UIControlStateNormal];
        self.currentPlayTime = 0;
        [self.playVoiceTimer invalidate];
        self.playVoiceTimer = nil;
    }
}
//界面消失时让界面小时转换录音按钮状态
-(void)viewWillDisappear:(BOOL)animated{
    [self.recorderBGView removeFromSuperview];
    _isRecorderWorking = NO;
    [self.btnmac setImage:[UIImage imageNamed:@"create_order_normal"] forState:UIControlStateNormal];
    self.btnmac.tag = ButtonTagRecorder;
}

@end
